
#include "config.h"
#include "fs.h"
#include "types.h"
#include "atomic.h"
#include "spinlock.h"
#include "fs_file.h"
#include "proc.h"
#include "sleeplock.h"
#include "stat.h"
#include "buf.h"
#include "bio.h"
#include "console.h"
#include "functions.h"
#include "string.h"
#include "file.h"
/*
struct {
  spinlock_t lock;
  struct inode inode[NINODE];
} itable;

struct superblock sb; 
// Find the inode with number inum on device dev
// and return the in-memory copy. Does not lock
// the inode and does not read it from disk.
//获取内存中的ｉｎｏｄｅ,不加锁，不读硬盘
static struct inode*
iget(uint dev, uint inum)
{
  if(DEBUG_INODE){
    printk("in iget\n");
  }
 struct inode *ip, *empty;

  acquire(&itable.lock);

  // Is the inode already in the table?
  empty = 0;
  for(ip = &itable.inode[0]; ip < &itable.inode[NINODE]; ip++){
    if(ip->ref > 0 && ip->dev == dev && ip->inum == inum){
      ip->ref++;
      release(&itable.lock);
      return ip;
    }
    if(empty == 0 && ip->ref == 0)    // Remember empty slot.
      empty = ip;
  }

  // Recycle an inode entry.
  if(empty == 0)
    panic("iget: no inodes");

  ip = empty;
  ip->dev = dev;
  ip->inum = inum;
  ip->ref = 1;
  ip->valid = 0;
  release(&itable.lock);
  if(DEBUG_INODE){
    printk("iget finished\n");
  }
  return ip;
}

// Increment referee count for ip.
// Returns ip to enable ip = idup(ip1) idiom.
struct inode*
idup(struct inode *ip)
{
  if(DEBUG_INODE){
    printk("in itable.lock is locked %d\n",itable.lock.lock);
     print_inode(ip);
  }
 
  acquire(&itable.lock);
  ip->ref++;
  release(&itable.lock);

  if(DEBUG_INODE){
    printk("end in itable.lock is locked %d\n",itable.lock.lock);
  }
  return ip;
}

// Copy the next path element from path into name.
// Return a pointer to the element following the copied one.
// The returned path has no leading slashes,
// so the caller can check *path=='\0' to see if the name is the last one.
// If no name to remove, return 0.
//
// Examples:
//   skipelem("a/bb/c", name) = "bb/c", setting name = "a"
//   skipelem("///a//bb", name) = "bb", setting name = "a"
//   skipelem("a", name) = "", setting name = "a"
//   skipelem("", name) = skipelem("////", name) = 0
//
static char*
skipelem(char *path, char *name)
{
  char *s;
  int len;

  while(*path == '/')
    path++;
  if(*path == 0)
    return 0;
  s = path;
  while(*path != '/' && *path != 0)
    path++;
  len = path - s;
  if(len >= DIRSIZ)
    memmove(name, s, DIRSIZ);
  else {
    memmove(name, s, len);
    name[len] = 0;
  }
  while(*path == '/')
    path++;
  return path;
}


// Free a disk block.
static void
bfree(int dev, uint b)
{
  struct buf *bp;
  int bi, m;

  bp = bread(dev, BBLOCK(b, sb));
  bi = b % BPB;
  m = 1 << (bi % 8);
  if((bp->data[bi/8] & m) == 0)
    panic("freeing free block");
  bp->data[bi/8] &= ~m;
  // log_write(bp);
  bwrite(bp);
  brelse(bp);
}


// // Truncate inode (discard contents).
// // Caller must hold ip->lock.
void
itrunc(struct inode *ip)
{
  int i, j;
  struct buf *bp;
  uint *a;

  for(i = 0; i < NDIRECT; i++){
    if(ip->addrs[i]){
      bfree(ip->dev, ip->addrs[i]);
      ip->addrs[i] = 0;
    }
  }

  if(ip->addrs[NDIRECT]){
    bp = bread(ip->dev, ip->addrs[NDIRECT]);
    a = (uint*)bp->data;
    for(j = 0; j < NINDIRECT; j++){
      if(a[j])
        bfree(ip->dev, a[j]);
    }
    brelse(bp);
    bfree(ip->dev, ip->addrs[NDIRECT]);
    ip->addrs[NDIRECT] = 0;
  }

  ip->size = 0;
  iupdate(ip);
}



// // Common idiom: unlock, then put.
void
iunlockput(struct inode *ip)
{
  iunlock(ip);
  iput(ip);
}


// Drop a reference to an in-memory inode.
// If that was the last reference, the inode table entry can
// be recycled.
// If that was the last reference and the inode has no links
// to it, free the inode (and its content) on disk.
// All calls to iput() must be inside a transaction in
// case it has to free the inode.
void
iput(struct inode *ip)
{
  acquire(&itable.lock);

  if(ip->ref == 1 && ip->valid && ip->nlink == 0){
    // inode has no links and no other references: truncate and free.

    // ip->ref == 1 means no other process can have ip locked,
    // so this acquiresleep() won't block (or deadlock).
    acquiresleep(&ip->lock);

    release(&itable.lock);

    itrunc(ip);
    ip->type = 0;
    iupdate(ip);
    ip->valid = 0;

    releasesleep(&ip->lock);

    acquire(&itable.lock);
  }

  ip->ref--;
  release(&itable.lock);
}


// Read the super block.
static void
readsb(int dev, struct superblock *sb)
{
  struct buf *bp;

  bp = bread(dev, 1);
  memmove(sb, bp->data, sizeof(*sb));
  brelse(bp);
}

void printSuperBLock(){
  printk("in printSuperBLock\n");
  printk("  magic %x\n",sb.magic);
  printk("  Size of file system image (blocks) %d \n",sb.size);
  printk("  Number of data blocks %d\n",sb.nblocks);
  printk("  Number of inodes %d\n",sb.ninodes);
  printk("  Number of log blocks %d\n",sb.nlog);
  printk("  Block number of first log block %d\n",sb.logstart);
  printk("  Block number of first inode block %d\n",sb.inodestart);
  printk("  Block number of first free map block %d\n",sb.bmapstart);
}
*/
// Init fs
void
fsinit(int dev) {
  file_t *file=file_open("fs.img", O_RDWR, 0);
  extern file_t  img_file;
  img_file.kfd=file->kfd;
  img_file.refcnt=file->refcnt;

  
    printk("in fsinit\n");
  

  if(DEBUG_INODE){
    printk("fsinit finished\n");
  }
  //  printSuperBLock();
  // initlog(dev, &sb);
}

/*
// Lock the given inode.
// Reads the inode from disk if necessary.
void
ilock(struct inode *ip)
{
  struct buf *bp;
  struct dinode *dip;

  if(ip == 0 || ip->ref < 1)
    panic("ilock");

  acquiresleep(&ip->lock);
  //从硬盘读取
  if(ip->valid == 0){
    if(DEBUG_INODE){
      printk("ip->inum %d\n",ip->inum);
      printk(" IBLOCK(ip->inum, sb) %d\n", IBLOCK(ip->inum, sb));

    }
    bp = bread(ip->dev, IBLOCK(ip->inum, sb));


    dip = (struct dinode*)bp->data + ip->inum%IPB;
    ip->type = dip->type;
    ip->major = dip->major;
    ip->minor = dip->minor;
    ip->nlink = dip->nlink;
    ip->size = dip->size;
    memmove(ip->addrs, dip->addrs, sizeof(ip->addrs));
    // brelse(bp);
    ip->valid = 1;
    if(DEBUG_INODE)
      printk(" dip->type %d \n", dip->type);
    if(ip->type == 0)
      panic("ilock: no type");
  }
}

// // Unlock the given inode.
void
iunlock(struct inode *ip)
{
  if(ip == 0 || !holdingsleep(&ip->lock) || ip->ref < 1)
    panic("iunlock");

  releasesleep(&ip->lock);
}

void print_inode(struct inode* inode){
  if(inode==0)
    panic("inode is empty");
  // in-memory copy of an inode
// struct inode {
//   uint dev;           // Device number
//   uint inum;          // Inode number
//   int ref;            // Reference count
//   struct sleeplock lock; // protects everything below here
//   int valid;          // inode has been read from disk?

//   short type;         // copy of disk inode
//   short major;
//   short minor;
//   short nlink;
//   uint size;
//   uint addrs[NDIRECT+1];
// };
 
  printk("in print_inode\n");
  printk("  Device number %d\n",inode->dev);
  printk("  Inode number %d\n",inode->inum);
  printk("  Reference count %d\n",inode->ref);
  printk("  sleeplock %p\n",inode->lock);
  printk("  sleeplock locked ? %d\n",inode->lock.locked);
  printk("  inode has been read from disk? %d\n",inode->valid);
  printk("  type %d\n",inode->type);
  printk("  major\n",inode->major);
  printk("  minor\n",inode->minor);
  printk("  nlink\n",inode->nlink);
  printk("  size %p \n",inode->size);
  printk("  addrs:");
  for(int i=0;i<13;i++){
    printk("  %d  ",inode->addrs[i]);
  }*//*
  printk("\n");
}

int
namecmp(const char *s, const char *t)
{
  return strncmp(s, t, DIRSIZ);
}

// Look for a directory entry in a directory.
// If found, set *poff to byte offset of entry.
//从目录结构中查找一个目录项
struct inode*
dirlookup(struct inode *dp, char *name, uint *poff)
{
  if(DEBUG_INODE){
    printk("in begin dirlookup\n");
  }
  uint off, inum;
  struct dirent de;
  //如果当前inode不是目录类型,则报错
  if(dp->type != T_DIR)
    panic("dirlookup not DIR");
  //遍历每个目录项，
  print_inode(dp);
  for(off = 0; off < dp->size; off += sizeof(de)){
    if(readi(dp, 0, (uint64)&de, off, sizeof(de)) != sizeof(de))
      panic("dirlookup read");
    if(de.inum == 0)
      continue;
    if(namecmp(name, de.name) == 0){
      // entry matches path element
      if(poff)
        *poff = off;
      inum = de.inum;
      return iget(dp->dev, inum);
    }
  }
  if(DEBUG_INODE){
    printk("in end dirlookup\n");
  }
  return 0;
}
// Look up and return the inode for a path name.
// If parent != 0, return the inode for the parent and copy the final
// path element into name, which must have room for DIRSIZ bytes.
// Must be called inside a transaction since it calls iput().
//获取ｐａｔｈ所对于的ｉｎｏｄｅ
//若标志位ｎａｍｅｉｐａｒｅｎｔ置位，则返回父目录对应的ｉｎｏｄｅ，并将父目录名用ｎａｍｅ返回

static struct inode*
namex(char *path, int nameiparent, char *name)
{
  if(DEBUG_INODE){
    printk("in namex\n");
     printk(" path %s \n",path);  
  // if(myproc())
    //  print_inode(myproc()->cwd);

  }

  struct inode *ip, *next;
  //获取根目录ｉｐ　或者获取进程当前目录ｉｐ
  if(*path == '/')
    ip = iget(ROOTDEV, ROOTINO);
  else
    ip = idup(myproc()->cwd);
  // printk("%d\n",ip->inum);
  //skipelem返回去掉最顶层目录的目录名，name返回最顶层目录名
  while((path = skipelem(path, name)) != 0){
    if(DEBUG_INODE){
      printk("in while  path %s \n",path);
    }	
    ilock(ip);
    if(ip->type != T_DIR){
      printk("ip->type != T_DIR\n");
     iunlockput(ip);
      return 0;
    }
    if(nameiparent && *path == '\0'){
      // Stop one level early.
      iunlock(ip);
      return ip;
    }
    if((next = dirlookup(ip, name, 0)) == 0){
      iunlockput(ip);
      return 0;
    }
    if(DEBUG_INODE){
      printk("in end dirlookup\n");
      // print_inode(ip);
    }
    iunlockput(ip);
    ip = next;
  }
   if(DEBUG_INODE){
      printk("in end while\n");
      // print_inode(ip);
    }
  if(nameiparent){
    iput(ip);
    return 0;
  }
  if(DEBUG_INODE){
      printk("is holding inode's lock? %d\n",ip->lock.locked);
      printk("namex finished  inode num %d\n",ip->inum);
    }
  return ip;
}

// Read data from inode.
// Caller must hold ip->lock.
// If user_dst==1, then dst is a user virtual address;
// otherwise, dst is a kernel address.
int
readi(struct inode *ip, int user_dst, uint64 dst, uint off, uint n)
{
  uint tot, m;
  struct buf *bp;

  if(off > ip->size || off + n < off)
    return 0;
  if(off + n > ip->size)
    n = ip->size - off;

  for(tot=0; tot<n; tot+=m, off+=m, dst+=m){
    bp = bread(ip->dev, bmap(ip, off/BSIZE));
    if(DEBUG_INODE){
      printk("in readi bread finished\n");
    }
    m = MIN(n - tot, BSIZE - off%BSIZE);
    if(either_copyout(user_dst, dst, bp->data + (off % BSIZE), m) == -1) {
      brelse(bp);
      tot = -1;
      break;
    }
    brelse(bp);
  }
  return tot;
}

struct inode*
nameiparent(char *path, char *name)
{
  return namex(path, 1, name);
  printk("in nameiparent finished\n");
}

// Inode content
//
// The content (data) associated with each inode is stored
// in blocks on the disk. The first NDIRECT block numbers
// are listed in ip->addrs[].  The next NINDIRECT blocks are
// listed in block ip->addrs[NDIRECT].

// Return the disk block address of the nth block in inode ip.
// If there is no such block, bmap allocates one.
//返回ip内第Ｎ个block在磁盘中的block　num
static uint
bmap(struct inode *ip, uint bn)
{
  uint addr, *a;
  struct buf *bp;

  if(bn < NDIRECT){
    if((addr = ip->addrs[bn]) == 0)
      ip->addrs[bn] = addr = balloc(ip->dev);
    return addr;
  }
  bn -= NDIRECT;

  if(bn < NINDIRECT){
    // Load indirect block, allocating if necessary.
    if((addr = ip->addrs[NDIRECT]) == 0)
      ip->addrs[NDIRECT] = addr = balloc(ip->dev);
    bp = bread(ip->dev, addr);
    a = (uint*)bp->data;
    if((addr = a[bn]) == 0){
      a[bn] = addr = balloc(ip->dev);
      bwrite(bp);
    }
    brelse(bp);
    return addr;
  }

  panic("bmap: out of range");
}

// Zero a block.
static void
bzero_r(int dev, int bno)
{
  struct buf *bp;

  bp = bread(dev, bno);
  memset(bp->data, 0, BSIZE);
  bwrite(bp);
  brelse(bp);
}
// Allocate a zeroed disk block.
static uint
balloc(uint dev)
{
  int b, bi, m;
  struct buf *bp;

  bp = 0;
  for(b = 0; b < sb.size; b += BPB){
    //读取存储block　b所在的bimmap的块的内容
    bp = bread(dev, BBLOCK(b, sb));
    //遍历该bit map
    for(bi = 0; bi < BPB && b + bi < sb.size; bi++){
      m = 1 << (bi % 8);
      if((bp->data[bi/8] & m) == 0){  // Is block free?
        bp->data[bi/8] |= m;  // Mark block in use.
        bwrite(bp);
        brelse(bp);
        bzero_r(dev, b + bi);
        return b + bi;
      }
    }
    brelse(bp);
  }
  panic("balloc: out of blocks");
}


struct inode*
namei(char *path)
{
  char name[DIRSIZ];
  //printk("in namei path %s \n",path);
  return namex(path, 0, name);
}

// void
// iput(struct inode *ip)
// {
//   acquire(&itable.lock);

//   if(ip->ref == 1 && ip->valid && ip->nlink == 0){
//     // inode has no links and no other references: truncate and free.

//     // ip->ref == 1 means no other process can have ip locked,
//     // so this acquiresleep() won't block (or deadlock).
//     acquiresleep(&ip->lock);

//     release(&itable.lock);

//     itrunc(ip);
//     ip->type = 0;
//     iupdate(ip);
//     ip->valid = 0;

//     releasesleep(&ip->lock);

//     acquire(&itable.lock);
//   }

//   ip->ref--;
//   release(&itable.lock);
// }

// // Common idiom: unlock, then put.
// void
// iunlockput(struct inode *ip)
// {
//   iunlock(ip);
//   iput(ip);
// }
void
iupdate(struct inode *ip)
{
  struct buf *bp;
  struct dinode *dip;

  bp = bread(ip->dev, IBLOCK(ip->inum, sb));
  dip = (struct dinode*)bp->data + ip->inum%IPB;
  dip->type = ip->type;
  dip->major = ip->major;
  dip->minor = ip->minor;
  dip->nlink = ip->nlink;
  dip->size = ip->size;
  memmove(dip->addrs, ip->addrs, sizeof(ip->addrs));
  bwrite(bp);
  brelse(bp);
}

// Allocate an inode on device dev.
// Mark it as allocated by  giving it type type.
// Returns an unlocked but allocated and referenced inode.
//在device上分配一个inode
//返回一个分配但为锁定的inode
struct inode*
ialloc(uint dev, short type)
{
  int inum;
  struct buf *bp;
  struct dinode *dip;

  for(inum = 1; inum < sb.ninodes; inum++){
    bp = bread(dev, IBLOCK(inum, sb));
    // printk("bread finished in ialloc %d\n",type);
    dip = (struct dinode*)bp->data + inum%IPB;
    if(dip->type == 0){  // a free inode
      memset(dip, 0, sizeof(*dip));
      dip->type = type;
      // printk("type in ialloc %d\n",type);
      bwrite(bp);   // mark it allocated on the disk
      brelse(bp);
      return iget(dev, inum);
    }
    brelse(bp);
  }
  panic("ialloc: no inodes");
}
// Write data to inode.
// Caller must hold ip->lock.
// If user_src==1, then src is a user virtual address;
// otherwise, src is a kernel address.
// Returns the number of bytes successfully written.
// If the return value is less than the requested n,
// there was an error of some kind.
int
writei(struct inode *ip, int user_src, uint64 src, uint off, uint n)
{
  uint tot, m;
  struct buf *bp;

  if(off > ip->size || off + n < off)
    return -1;
  if(off + n > MAXFILE*BSIZE)
    return -1;

  for(tot=0; tot<n; tot+=m, off+=m, src+=m){
    bp = bread(ip->dev, bmap(ip, off/BSIZE));
    m = MIN(n - tot, BSIZE - off%BSIZE);
    if(either_copyin(bp->data + (off % BSIZE), user_src, src, m) == -1) {
      brelse(bp);
      break;
    }
    bwrite(bp);
    brelse(bp);
  }

  if(off > ip->size)
    ip->size = off;

  // write the i-node back to disk even if the size didn't change
  // because the loop above might have called bmap() and added a new
  // block to ip->addrs[].
  iupdate(ip);

  return tot;
}

// Write a new directory entry (name, inum) into the directory dp.
int
dirlink(struct inode *dp, char *name, uint inum)
{
  int off;
  struct dirent de;
  struct inode *ip;

  // Check that name is not present.
  if((ip = dirlookup(dp, name, 0)) != 0){
    iput(ip);
    return -1;
  }

  // Look for an empty dirent.
  for(off = 0; off < dp->size; off += sizeof(de)){
    if(readi(dp, 0, (uint64)&de, off, sizeof(de)) != sizeof(de))
      panic("dirlink read");
    if(de.inum == 0)
      break;
  }

  strncpy(de.name, name, DIRSIZ);
  de.name[DIRSIZ-1] = '\0';
  de.inum = inum;
  if(writei(dp, 0, (uint64)&de, off, sizeof(de)) != sizeof(de))
    panic("dirlink");

  return 0;
}
*/